<template>
  <div class="app-container">
    <div class="content-card">
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="图书编号">
            <el-input v-model="search1" placeholder="请输入图书编号" clearable>
              <template #prefix><el-icon class="el-input__icon"><Search /></el-icon></template>
            </el-input>
          </el-form-item>
          <el-form-item label="图书名称">
            <el-input v-model="search2" placeholder="请输入图书名称" clearable>
              <template #prefix><el-icon class="el-input__icon"><Search /></el-icon></template>
            </el-input>
          </el-form-item>
          <el-form-item label="借阅者" v-if="user.role == 1">
            <el-input v-model="search3" placeholder="请输入借阅者昵称" clearable>
              <template #prefix><el-icon class="el-input__icon"><Search /></el-icon></template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="load">
              <el-icon><Search /></el-icon>查询
            </el-button>
            <el-button @click="clear">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮 -->
      <div class="operation-bar" v-if="user.role == 1">
        <el-popconfirm title="确认删除选中记录?" @confirm="deleteBatch">
          <template #reference>
            <el-button type="danger" :disabled="!forms.length">
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
          </template>
        </el-popconfirm>
      </div>

      <!-- 数据表格 -->
      <el-table 
        :data="tableData" 
        stripe 
        border 
        @selection-change="handleSelectionChange"
        header-cell-class-name="table-header"
      >
        <el-table-column v-if="user.role == 1" type="selection" width="55" align="center" />
        <el-table-column prop="isbn" label="图书编号" sortable min-width="120" />
        <el-table-column prop="bookName" label="图书名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="nickName" label="借阅者" min-width="100" />
        <el-table-column prop="lendtime" label="借阅时间" min-width="160" />
        <el-table-column prop="deadtime" label="最迟归还日期" min-width="160" />
        <el-table-column prop="prolong" label="可续借次数" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.prolong > 0 ? 'success' : 'danger'">{{ scope.row.prolong }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <el-button v-if="user.role == 1" type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>修改
            </el-button>
            <el-popconfirm v-if="user.role == 1" title="确认删除该记录?" @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button type="danger" link>
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm 
              v-if="user.role == 2" 
              title="确认续借(续借一次延长30天)?" 
              @confirm="handlereProlong(scope.row)"
              :disabled="scope.row.prolong == 0"
            >
              <template #reference>
                <el-button type="primary" link :disabled="scope.row.prolong == 0">
                  <el-icon><Timer /></el-icon>续借
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible2" title="修改借阅信息" width="500px" destroy-on-close>
      <el-form :model="form" label-width="100px">
        <el-form-item label="图书编号">
          <el-input v-model="form.isbn" disabled></el-input>
        </el-form-item>
        <el-form-item label="图书名称">
          <el-input v-model="form.bookName" disabled></el-input>
        </el-form-item>
        <el-form-item label="借阅者">
          <el-input v-model="form.nickName" disabled></el-input>
        </el-form-item>
        <el-form-item label="续借次数">
          <el-input-number v-model="form.prolong" :min="0" :max="10" style="width: 100%"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from "../utils/request";
import { ElMessage } from "element-plus";
import moment from "moment";
import { Search, Refresh, Delete, Edit, Timer } from '@element-plus/icons-vue'

export default {
  name: 'bookwithuser',
  components: {
    Search, Refresh, Delete, Edit, Timer
  },
  data() {
    return {
      form: {},
      dialogVisible2: false,
      search1: '',
      search2: '',
      search3: '',
      total: 0,
      currentPage: 1,
      pageSize: 10,
      tableData: [],
      user: {},
      forms: [],
    }
  },
  created() {
    let userStr = sessionStorage.getItem("user") || "{}"
    this.user = JSON.parse(userStr)
    this.load()
  },
  methods: {
    handleSelectionChange(val) {
      this.forms = val
    },
    deleteBatch() {
      if (!this.forms.length) {
        ElMessage.warning("请选择数据！")
        return
      }
      request.post("bookwithuser/deleteRecords", this.forms).then(res => {
        if (res.code === '0') {
          ElMessage.success("批量删除成功")
          this.load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    },
    load() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        search1: this.search1,
        search2: this.search2,
      }
      
      if (this.user.role == 1) {
        params.search3 = this.search3
      } else {
        params.search3 = this.user.id
      }

      request.get("/bookwithuser", { params }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    clear() {
      this.search1 = ""
      this.search2 = ""
      this.search3 = ""
      this.load()
    },
    handleDelete(row) {
      const form3 = JSON.parse(JSON.stringify(row))
      request.post("bookwithuser/deleteRecord", form3).then(res => {
        if (res.code == 0) {
          ElMessage.success("删除成功")
          this.load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    },
    handlereProlong(row) {
      var nowDate = new Date(row.deadtime);
      nowDate.setDate(nowDate.getDate() + 30);
      row.deadtime = moment(nowDate).format("yyyy-MM-DD HH:mm:ss");
      row.prolong = row.prolong - 1;
      request.post("/bookwithuser", row).then(res => {
        if (res.code == 0) {
          ElMessage.success('续借成功')
          this.load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    },
    save() {
      request.post("/bookwithuser", this.form).then(res => {
        if (res.code == 0) {
          ElMessage.success('修改信息成功')
          this.dialogVisible2 = false
          this.load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible2 = true
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum
      this.load()
    },
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: var(--color-bg-1);
  min-height: calc(100vh - 60px);
}

.content-card {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-box {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--color-border);
}

.operation-bar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.table-header) {
  background-color: var(--color-fill-2) !important;
  color: var(--color-text-1);
  font-weight: 600;
}
</style>
